package com.li.onjava8.concurrent.cf.deadlock;

import com.li.onjava8.concurrent.utils.Nap;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

public class DiningPhilosophers {

    private StickHolder[] sticks;
    private Philosopher[] philosophers;

    public DiningPhilosophers(int n) {
        //五根筷子
        sticks = new StickHolder[n];
        Arrays.setAll(sticks, i -> new StickHolder());
        philosophers = new Philosopher[n];
        //每位哲学家从左到右拿起筷子
        Arrays.setAll(philosophers, i -> new Philosopher(i, sticks[i], sticks[(i+1)%n]));
        Arrays.stream(philosophers)
                .forEach(CompletableFuture::completedFuture);
    }

    public static void main(String[] args) {
        // 初始化五位哲学家
        new DiningPhilosophers(5);
        new Nap(3, "Shutdown");
    }
}
